import axios from 'axios'
import { getToken, removeToken } from './auth'
import { Message } from 'element-ui'
import router from '@/router'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }

    // if (config.baseURL === 'https://api-hmzs.itheima.net/tj') {
    //   config.headers['Content-Type'] = 'multipart/form-data'
    // }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      Message.error('当前登录状态已过期，请重新登录')
      removeToken()
      router.push(router.app.$route.query.redirect)
    }
    Message.error(error.response.data.msg)
    return Promise.reject(error)
  }
)

export default service
